import React, { useState, useEffect } from 'react';
import cn from 'classnames';
import moment from 'moment';
import s from './style.module.css';
import i from '@/index.module.css';
import { getPartTime, getHoursTime, getErrorMessage } from '@/common/constant';
import { Select, Confirm, Pagination, Table, Button, Message, Datetime } from '@knownsec/react-component';
import { downloadLog, defenseLogDown, batchDeleteLog } from '~/API/index';

export default function DefenseLog() {
  const today = [moment().subtract(24, 'hours'), moment()];
  const [now, setNow] = useState(today);
  const [refre, setRefre] = useState(false);
  const [batch, setBatch] = useState([]);
  const defaults = {
    最近24h: [moment().subtract(24, 'hours'), moment()],
    最近7天: [moment().subtract(6, 'days').hours(0).minutes(0).seconds(0), moment()],
    最近30天: [moment().subtract(29, 'days').hours(0).minutes(0).seconds(0), moment()],
  };
  const [timeList, setTimeList] = useState([]);
  const [filter, setFilter] = useState({
    page: 1,
    page_size: 10,
    type: 'attack',
    start_date: now[0].format('YYYY-MM-DD'),
    end_date: now[1].format('YYYY-MM-DD'),
  });
  const [total, setTotal] = useState([]);
  const [selValue, setSelValue] = useState(['attack']);
  const [loading, setLoading] = useState(false);
  useEffect(() => {
    getTableData();
  }, []);
  const getTableData = (fil) => {
    setLoading(true);
    defenseLogDown('GET', fil || filter)
      .then((res) => {
        const arr = res.data.data.map((item, index) => {
          return { time: item, id: index, query: item };
        });
        setLoading(false);
        setTimeList(arr);
        setTotal(res.data.total);
        setRefre(!refre);
        setBatch([]);
      })
      .catch((err) => Message.show({ type: 'error', message: getErrorMessage(err) }));
  };
  const columns = [
    { title: '时间', key: 'time', dataIndex: 'time' },
    {
      title: '操作',
      key: 'make',
      render: (cur, item) => {
        return (
          <>
            <span
              onClick={() => downloadLog('GET', { responseType: 'blob' }, selValue[0], item.query)}
              className={cn(i.mainColor, i.cp)}
            >
              下载
            </span>
            <span className={cn(i.ml10, i.mainColor)} onClick={() => batchDelete(item.time)}>
              删除
            </span>
          </>
        );
      },
    },
  ];
  const option = [
    { label: '攻击日志', value: 'attack' },
    { label: '访问日志', value: 'access' },
  ];
  const changeTime = (val) => {
    const obj = Object.assign({}, filter);
    obj.start_date = val[0].format('YYYY-MM-DD');
    obj.end_date = val[1].format('YYYY-MM-DD');
    setNow(val);
    setFilter(obj);
  };
  const getList = (val) => {
    setBatch(val);
    setRefre(!refre);
  };
  const batchDownLoad = () => {
    const arr = [];
    timeList.forEach((item) => {
      if (batch.indexOf(item.id) > -1) {
        arr.push(item);
      }
    });
    arr.forEach((item) => {
      downloadLog('GET', { responseType: 'blob' }, selValue[0], item.query);
    });
  };
  const batchDelete = (it) => {
    const arr = [];
    timeList.forEach((item) => {
      if (batch.indexOf(item.id) > -1) {
        arr.push(item.time);
      }
    });
    Confirm({
      title: '提示',
      pro: true,
      message: (
        <div className={cn(i.tac, i.mb10)}>你确定要{it ? '删除' : '批量删除选中的'}日志吗？</div>
      ),
      onconfirm: () => {
        batchDeleteLog('DELETE', { type: filter.type, date_list: it ? [it] : arr })
          .then((res) => {
            Message.show({
              type: res.status,
              message: res.message,
              onclose() {
                getTableData(filter);
              },
            });
          })
          .catch((err) => Message.show({ type: 'error', message: getErrorMessage(err) }));
      },
    });
  };
  const disabledate = (current) => {
    return current > moment() || current < moment().subtract(6, 'month');
  };
  return (
    <div className={cn(i.pt24, i.pl20, i.pr20)}>
      <div className={cn(i.df, i.aic)}>
        <Select
          placeholder="请选择日志类型"
          option={option}
          value={selValue}
          clearable
          onChange={({ selectedItem }) => {
            setSelValue([selectedItem[0]?.value || '']);
            const obj = Object.assign({}, filter);
            obj.type = selectedItem[0]?.value || '';
            setFilter(obj);
          }}
        />
        <div className={cn(i.pr, i.dib)}>
          <Datetime
            disabledDate={disabledate}
            useDefault={defaults}
            semiYear
            allowClear={false}
            value={now}
            format={'YYYY-MM-DD'}
            showTime={false}
            className={cn(i.ml10, s.dt)}
            onChange={changeTime}
          />
        </div>
        <Button type="primary" className={cn(i.ml10)} onClick={() => getTableData()}>
          查询
        </Button>
        <Button
          type="default"
          className={i.ml10}
          onClick={() => {
            setSelValue(['attack']);
            setNow(today);
            setBatch([]);
            setRefre(!refre);
            const obj = {
              page: 1,
              pageSize: 10,
              type: 'attack',
              start_date: today[0].format('YYYY-MM-DD'),
              end_date: today[1].format('YYYY-MM-DD'),
            };
            setFilter(obj);
            getTableData(obj);
          }}
        >
          重置
        </Button>
      </div>
      <div className={i.pt20}>
        <span
          className={cn(
            i.dib,
            i.mb10,
            batch.length ? i.cp : i.cna,
            batch.length ? i.mainColor : i.borderColor
          )}
          onClick={() => {
            batch.length && batchDownLoad();
          }}
        >
          批量下载
        </span>
        <span
          className={cn(
            i.dib,
            i.mb10,
            i.ml10,
            batch.length ? i.cp : i.cna,
            batch.length ? i.mainColor : i.borderColor
          )}
          onClick={() => {
            batch.length && batchDelete();
          }}
        >
          批量删除
        </span>
        <Table
          refre={refre}
          selectable
          key={filter}
          columns={columns}
          tableLoading={loading}
          loadingLabel=""
          data={timeList}
          getCheckedList={getList}
        />
      </div>
      {!!total && (
        <div className={cn(i.pt20, i.df, i.aic, i.jcfe, i.pb20)}>
          {total > 10 && <Pagination
            key={filter}
            total={total}
            showQuickJumper={{ goButton: true }}
            showSizeChanger={true}
            pageSizeOptions={['10', '20', '50']}
            current={filter.page}
            onChange={(page, pageSize) => {
              const obj = Object.assign({}, filter);
              obj.page = page;
              obj.page_size = pageSize;
              setFilter(obj);
              setBatch([]);
              setRefre(!refre);
            }}
          />}
        </div>
      )}
    </div>
  );
}
